## Title: OGR utility functions for the modified pylas.
## Modified By: Christian Everhart
## Creation date: Before May 06, 2012
## Purpose: To act as utility functions for reading ogr datasource/layer/features for building LAS QA/QC tools used by the mod_pylas Python package.

## Modifications
## May 06, 2012 - Prepare code for release 0.1 (google code)


import ogr,os

def getFeatureBoundingAndAttributeDataFromPath(ogrPath,attList):
    listReturn = []
    ogrLayer = getOgrLayerFromPath(ogrPath)
    if ogrLayer is not None:
        featureList = getFeatureList(ogrLayer)
        for ftr in featureList:
            listReturn.append(getBoundingGeomAndAttVals(ftr, attList))
    return listReturn
    ## print listReturn

def getFieldNamesFromPath(ogrPath):
    listAttNames = []
    ogrLayer = getOgrLayerFromPath(ogrPath)
    if ogrLayer is not None:
        listAttNames = getLayerFieldNameList(ogrLayer)
    return listAttNames
    

def getOgrLayerFromPath(ogrPath):
    outLayer = None
    if os.path.exists(ogrPath):
        outDataSource = ogr.Open(ogrPath)
        if outDataSource is not None:
            outLayer = outDataSource.GetLayer()
            return outLayer

def getLayerFieldNameList(ogrLayer):
    fieldnameList = []
    if ogrLayer.__class__ is ogr.Layer:
        ogrLayerDefn = ogrLayer.GetLayerDefn()
        for x in range(0,ogrLayerDefn.GetFieldCount() - 1):
            fieldnameList.append(ogrLayerDefn.GetFieldDefn(x).GetName())
    return fieldnameList
        
def getFeatureList(ogrLayer):
    featureList = []
    if ogrLayer.__class__ is ogr.Layer:
        for x in range(0,ogrLayer.GetFeatureCount() - 1):
            featureList.append(ogrLayer.GetFeature(x))
    return featureList

def getBoundingGeomAndAttVals(ogrFeature, listAttNames):
    ## [(minx,miny,maxx,maxy),[{attName1:attValue1},{attName2:attValue2}]]
    listAttValsAndGeom = []
    ogrGeometry = ogrFeature.GetGeometryRef()
    
    if ogrGeometry is not None:
        listAttValsAndGeom.append(ogrGeometry.GetEnvelope())
        
    if ogrFeature.__class__ is ogr.Feature:
        ogrGeometry = ""

        ogrFeatDefn = ogrFeature.GetDefnRef()
        listAttVals = []
        for attName in listAttNames:
            attInd = ogrFeatDefn.GetFieldIndex(attName)
            if attInd > -1:
                attValue = ogrFeature.GetField(attInd)
                listAttVals.append({attName:attValue})
        listAttValsAndGeom.append(listAttVals)
    return listAttValsAndGeom
    
## ogrDS = ogr.Open(r'C:\Temp\SHP\STATEWIDE\COUNTIES.shp')
## ogrLYR = ogrDS.GetLayer()
## getFeatureList(ogrLYR)

## getFeatureDataFromPath(r'C:\Temp\SHP\STATEWIDE\COUNTIES.shp',[])
